package com.shujia.flink.core;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Demo2JavaWordCount {
    public static void main(String[] args) throws Exception {
        //1、创建flink的环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2、读取数据
        DataStream<String> linesDS = env.socketTextStream("master", 8888);

        //3、一行转换成多行
        DataStream<String> wordsDS = linesDS.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] split = value.split(",");
                for (String word : split) {
                    //将数据发送到下游
                    out.collect(word);
                }
            }
        });

        //4、转换成kv格式
        //java中的lambda表达式
        //DataStream<Tuple2<String, Integer>> kvDS = wordsDS.map(value -> Tuple2.of(value, 1));
        //Tuple2 :二元组,相当于scala中的 (k，v)
        DataStream<Tuple2<String, Integer>> kvDS = wordsDS.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });


        //5、按照单词分组
        //KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(value -> value.f0);
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });
        //6、统计单词的数量
        DataStream<Tuple2<String, Integer>> countDS = keyByDS.sum(1);

        countDS.print();

        env.execute();
    }
}
